<?php 

namespace pmvc\mvc\security;

use pmvc\mvc\Request;

class SecurityUtil {

	const PMVC_SESSION_USER	= "__pmvc_security_User";

	public static function setCurrentUser(Request $request, User $user) {
		if ($user==NULL) {
			self::clear($request);
		} else {
			$request->setSessionVariable(self::PMVC_SESSION_USER, $user);
		}
	}

	public static function getCurrentUser(Request $request) {
		return ($request->hasSessionVariable(self::PMVC_SESSION_USER))
			? $request->getSessionVariable(self::PMVC_SESSION_USER)
			: NULL;
	}

	public static function hasAllRoles(Request $request, Array $roles, User $user=null) {
		if (!isset($user)) {
			$user = self::getCurrentUser($request);
		}
		if (!isset($user)) {
			return false;
		}
		// check the roles
	    $userRoles = array_intersect($user->getRoles(), $roles);
	    return count($userRoles)==count($roles);
	}

	public static function hasAnyRoles(Request $request, Array $roles, User $user=null) {
		if (!isset($user)) {
			$user = self::getCurrentUser($request);
		}
		if (!isset($user)) {
			return false;
		}
		// check the roles
	    $userRoles = array_intersect($user->getRoles(), $roles);
	    return count($userRoles)>0;
	}

	public static function isMissingAllRoles(Request $request, Array $roles, User $user=null) {
		if (!isset($user)) {
			$user = self::getCurrentUser($request);
		}
		if (!isset($user)) {
			return true;
		}
		// check the roles
	    $userRoles = array_intersect($user->getRoles(), $roles);
	    return count($userRoles)==0;
	}

	public static function isMissingAnyRoles(Request $request, Array $roles, User $user=null) {
		if (!isset($user)) {
			$user = self::getCurrentUser($request);
		}
		if (!isset($user)) {
			return true;
		}
		// check the roles
	    $userRoles = array_intersect($user->getRoles(), $roles);
		return count($userRoles)<count($roles);
	}

	public static function isLoggedIn(Request $request) {
		return $request->hasSessionVariable(self::PMVC_SESSION_USER);
	}

	public static function clear(Request $request) {
		$request->removeSessionVariable(self::PMVC_SESSION_USER);
	}

}

?>